﻿using WeixinSB.Common;
using WeixinSB.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Windows.Input;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using LYL.Common.RT.Text;
using WeixinSB.Model;
using Windows.Storage;
using WeixinSB.View;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Graphics.Imaging;
using System.Threading.Tasks;
using Windows.ApplicationModel.Store;
using WeixinSB.Tools;
using Windows.UI;
using WeixinSB.Service;
using System.Collections.ObjectModel;
using WeixinSb.Model;

// The Pivot Application template is documented at http://go.microsoft.com/fwlink/?LinkID=391641

namespace WeixinSB.View
{
    /// <summary>
    /// A page that displays details for a single item within a group.
    /// </summary>
    public sealed partial class HomePage : Page
    {

        string maxId = "0";

        public readonly ObservableCollection<WeiXinUploadModel> home = new ObservableCollection<WeiXinUploadModel>();

        //private readonly NavigationHelper navigationHelper;
        private readonly ObservableDictionary defaultViewModel = new ObservableDictionary();

        private string html = "";
        public HomePage()
        {
            this.InitializeComponent();

            lv.ItemsSource = home;

            //this.navigationHelper = new NavigationHelper(this);
            //this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
            //this.navigationHelper.SaveState += this.NavigationHelper_SaveState;

            Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
        }

        void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
        {
            e.Handled = true;
            if (web.Visibility == Windows.UI.Xaml.Visibility.Visible)
            {
                sbWebEnd.Begin();
                HideImageBar();
                return;
            }
            if (Frame.CanGoBack)
            {
                Frame.GoBack();
            }
        }

        /// <summary>
        /// Gets the <see cref="NavigationHelper"/> associated with this <see cref="Page"/>.
        /// </summary>
        //public NavigationHelper NavigationHelper
        //{
        //    get { return this.navigationHelper; }
        //}

        /// <summary>
        /// Gets the view model for this <see cref="Page"/>.
        /// This can be changed to a strongly typed view model.
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        /// <summary>
        /// Populates the page with content passed during navigation. Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>.
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            // TODO: Create an appropriate data model for your problem domain to replace the sample data.
            //var item = await SampleDataSource.GetItemAsync((string)e.NavigationParameter);
            //this.DefaultViewModel["Item"] = item;
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/>.</param>
        /// <param name="e">Event data that provides an empty dictionary to be populated with
        /// serializable state.</param>
        private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
            // TODO: Save the unique state of the page here.
        }

        #region NavigationHelper registration

        /// <summary>
        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// <para>
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="NavigationHelper.LoadState"/>
        /// and <see cref="NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.
        /// </para>
        /// </summary>
        /// <param name="e">Provides data for navigation methods and event
        /// handlers that cannot cancel the navigation request.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync();

            Uri dataUri = new Uri("ms-appx:///Html/ImageView.html");
            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);
            html = await FileIO.ReadTextAsync(file);

            if (e.NavigationMode == NavigationMode.Back)
            {
                return;
            }

            await Load();

            //this.navigationHelper.OnNavigatedTo(e);

        }



        private async Task Load()
        {
            try
            {
                pr.Visibility = Windows.UI.Xaml.Visibility.Visible;
                UploadService service = new UploadService();
                var result = await service.List(maxId);
                if (result.Ret && result.DataModel != null)
                {
                    if (maxId == "0")
                    {
                        home.Clear();
                    }
                    foreach (var item in result.DataModel)
                    {
                        home.Add(item);
                        maxId = item.Id;
                    }
                }
                pr.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }
            catch (Exception ex)
            {

            }

        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            //this.navigationHelper.OnNavigatedFrom(e);
        }

        #endregion


        private void Edit_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(MainPage));
        }


        private async void Reflesh_Click(object sender, RoutedEventArgs e)
        {
            maxId = "0";
            await Load();
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {

        }

        void HideImageBar()
        {
            Refresh.Visibility = Windows.UI.Xaml.Visibility.Visible;
            ViewAll.Visibility = Windows.UI.Xaml.Visibility.Visible;
            Save.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
        }

        void ShowImageBar()
        {
            Refresh.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            ViewAll.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            Save.Visibility = Windows.UI.Xaml.Visibility.Visible;
        }
        //private void Item_Tapped(object sender, TappedRoutedEventArgs e)
        //{
        //    var model = lv.SelectedItem as WeiXinUploadModel;
        //    if (model != null)
        //    {
        //        web.NavigateToString(string.Format(html, model.ImagePath));
        //        sbWebBegin.Begin();
        //    }
        //}

        private void Image_Tapped(object sender, TappedRoutedEventArgs e)
        {
            var img = sender as Image;
            if (img != null)
            {
                var model = img.DataContext as WeiXinUploadModel;
                if (model != null)
                {
                    ShowImageBar();
                    web.NavigateToString(html.Replace("$src$", model.ImagePath));
                    sbWebBegin.Begin();
                }
            }
        }
    }
}